package 二叉树相关问题.经典二叉树问题;

import java.util.LinkedList;

//297
public class 二叉树的序列化和反序列化 {
    //序列化
    public String serialize(TreeNode root) {
        StringBuilder builder = new StringBuilder();
        serialize(root,builder);
        return builder.toString();
    }
    public void serialize(TreeNode root,StringBuilder builder) {
         if (root==null){
             builder.append("#").append(",");
             return;
         }
         builder.append(root.val).append(",");
         serialize(root.left,builder);
         serialize(root.right,builder);
    }
    //反序列化
    public TreeNode deserialize(String data) {
        LinkedList<String> list = new LinkedList<>();
        for (String s: data.split(",")) {
            list.addLast(s);
        }
        return deserialize(list);
    }
    public TreeNode deserialize( LinkedList<String> list) {
        if (list.size()==0)
            return null;
        String s = list.removeFirst();
        if (s.equals("#"))
            return null;
        TreeNode root = new TreeNode(Integer.parseInt(s));
        root.left=deserialize(list);
        root.right=deserialize(list);
        return root;
    }
}
